import React, { useState } from 'react';
import { Menu, Button, Tabs, Dropdown, Spin } from 'antd';
import { connect, Dispatch } from 'umi';
import { FilePdfOutlined, UploadOutlined } from '@ant-design/icons';
import { isArray, isEmpty, findIndex } from 'lodash';
import { UploadFile } from 'antd/lib/upload/interface';
import { ClickParam } from 'antd/lib/menu';
import IssueList from './IssueList';
import UploadBlueprint, { CreateBlueprintForm } from './UploadBlueprint';

import { StateType } from './model';
import { BlueprintItem } from '../data';

const { SubMenu, ItemGroup } = Menu;

const getBlueprint = (data: BlueprintItem[], key: string) => {
  let blueprint = null;
  data.forEach((m) => {
    const { subItem: blueprints = [] } = m;
    blueprints.forEach((b) => {
      if (b.id === key) {
        blueprint = b;
      }
    });
  });
  return blueprint;
};

export interface MyMenuDataItem {
  submenu?: MyMenuDataItem[];
  icon?: React.ReactNode;
  title: string;
  key: string;
  parentKeys?: string[];
  url?: string;
  file?: UploadFile;
}

export interface BlueprintMenuProps {
  height: number;
  loading: boolean;
  project: StateType;
  dispatch: Dispatch;
  data: BlueprintItem[];
  onBlueprintSelect: (url?: string) => void;
  onIssueSelect: (url: string, marks: any[]) => void;
  onCollapsed: (val: any) => void;
}

const BlueprintMenu: React.FC<BlueprintMenuProps> = (props) => {
  const {
    loading,
    height,
    project: {
      pdfLoading,
      oPdfLoading,
      mPdfLoading,
      activeTabKey,
      unitProject,
      bpHistory,
      blueprintList,
      majorMenuState,
      issueListState,
    },
    dispatch,
    onBlueprintSelect,
    onIssueSelect,
    onCollapsed,
  } = props;

  const {
    selectedBp,
    selectedKey,
    openKeys,
  } = majorMenuState;

  const [uploadModalVisible, setUploadModalVisible] = useState(false);
  const [selectedUrl, setSelectedUrl] = useState('');
  const [key, setKey] = useState('');
  // const [bpHistory, setBpHistory] = useState<any[]>([]);

  const onUploadPdf = (targetKey: string, formValues: CreateBlueprintForm) => {
    if (unitProject) {
      dispatch({
        type: 'project/addBlueprint',
        payload: {
          mid: targetKey,
          formValues,
        },
        callback: (success: boolean, bp: any) => {
          if (success) {
            setUploadModalVisible(false);
            setSelectedUrl(bp.url);
            onBlueprintSelect(bp.url);
          }
        },
      });
    }
  };

  const onUploadPdfClick = (sk: string) => {
    setKey(sk);
    setSelectedUrl('');
    onBlueprintSelect('');
    setUploadModalVisible(true);
    dispatch({
      type: 'project/save',
      payload: {
        majorMenuState: {
          ...majorMenuState,
          selectedBp: {},
          selectedKey: '',
        },
        pdfMarkable: false,
        drawingUrl: '',
        drawingMarks: [],
      }
    });
  };

  const handleIssueSelect = (issue: any) => {
    if (!isEmpty(selectedUrl)) {
      onIssueSelect(
        selectedUrl,
        issue.marks.map((d: any) => JSON.parse(d.data)),
      );
    }
  };

  const handleHistoryBpSelect = (bp: any) => {
    onBlueprintSelect(bp && bp.url);
  };

  const handleBlueprintSelect = (e: ClickParam) => {
    const blueprint = getBlueprint(blueprintList, e.key);
    const { url = '' } = blueprint || { url: '' };
    dispatch({
      type: 'project/save',
      payload: {
        majorMenuState: {
          ...majorMenuState,
          selectedBp: blueprint,
          selectedKey: e.key,
        },
        issueListState: {
          ...issueListState,
          expandedKeys: [],
          checkedKeys: [],
          selectedKeys: [],
          autoExpandParent: false,
          selectedBph: [],
        },
        compareList: [],
        drawingUrl: url,
        drawingMarks: [],
      }
    });
  };

  const handleFetchBlueprint = (mid: string) => {
    if (unitProject) {
      dispatch({
        type: 'project/fetchBlueprint',
        payload: mid,
        callback: (success) => {
          if (success) {
            setUploadModalVisible(false);
          }
        },
      });
    }
  };

  const handleTitleClick = (e: any, id: string) => {
    const index = findIndex(openKeys, (k) => k === e.key);
    if (index < 0) {
      openKeys.push(e.key);
    } else {
      openKeys.splice(index, 1);
    }
    dispatch({
      type: 'project/save',
      payload: {
        issueListState: {
          ...issueListState,
          expandedKeys: [],
          checkedKeys: [],
          selectedKeys: [],
          autoExpandParent: false,
          selectedBph: [],
        },
        majorMenuState: {
          ...majorMenuState,
          openKeys,
          selectedKey: '',
          selectedBp: {},
        },
        compareList: [],
        drawingUrl: '',
        drawingMarks: [],
      },
    });
    setSelectedUrl('');
    if (index < 0) {
      // 查询单体
      handleFetchBlueprint(id);
    }
  }

  const renderMenu = (menuData: BlueprintItem[], level: number = 0) => {
    if (isArray(menuData) && !isEmpty(menuData)) {
      return menuData.map((item) => {
        const { id, mid, title, version, subItem = [] } = item;
        if (level === 0) {
          // 专业
          return (
            <SubMenu
              key={id}
              title={title}
              onTitleClick={(e) => {
                handleTitleClick(e, id);
              }}
            >
              {renderMenu(subItem, level + 1)}
              <ItemGroup
                key={`${id}-upload`}
                title={
                  <Button
                    type="link"
                    icon={<UploadOutlined />}
                    onClick={() => {
                      onUploadPdfClick(id);
                    }}
                  >
                    上传图纸
                  </Button>
                }
              />
            </SubMenu>
          );
        }
        if (level === 1) {
          // 图纸
          return (
            <Menu.Item icon={<FilePdfOutlined />} key={id}>
              <Dropdown
                overlay={
                  <Menu>
                    <Menu.Item key="1">删除</Menu.Item>
                    <Menu.Item key="2">修改</Menu.Item>
                    <Menu.Item
                      key="3"
                      onClick={() => {
                        setKey(mid);
                        setUploadModalVisible(true);
                      }}
                    >
                      复审上传
                    </Menu.Item>
                  </Menu>
                }
                trigger={['contextMenu']}
              >
                <a title="鼠标右键更多操作">
                  {`${title}-${version === 0 ? '初审' : `第${version}次复审`}`}
                </a>
              </Dropdown>
            </Menu.Item>
          );
        }
        return null;
      });
    }
    return null;
  };

  const handleIssueSave = (bhid?: string, opinion?: string, drawingMarks?: any) => {
    dispatch({
      type: 'project/addIssue',
      payload: {
        bhid,
        opinion,
        marks: drawingMarks,
      },
    });
  };

  return (
    <Spin spinning={loading || pdfLoading || oPdfLoading || mPdfLoading} >
      <Tabs
        type="card"
        defaultActiveKey="1"
        activeKey={activeTabKey}
        onChange={(activeKey) => {
          if (activeKey === '2') {
            dispatch({
              type: 'project/fetchBlueprintIssue',
              payload: {
                bid: selectedBp.id,
              },
            });
          }
          dispatch({
            type: 'project/save',
            payload: {
              activeTabKey: activeKey,
              editIssueCollapsed: true,
              editIssueReadonly: true,
              editIssueFormValues: {
                bhid: '',
              },
            }
          });
        }}
      >
        <Tabs.TabPane key="1" tabKey="1" tab="图纸信息">
          <Menu
            style={{ height, overflowY: 'auto' }}
            theme="light"
            mode="inline"
            selectedKeys={[selectedKey]}
            openKeys={openKeys}
            onClick={(e) => handleBlueprintSelect(e)}
          >
            {renderMenu(blueprintList, 0)}
          </Menu>
        </Tabs.TabPane>
        <Tabs.TabPane
          key={2}
          tabKey="2"
          tab="审查意见"
          disabled={isEmpty(selectedBp) || !selectedBp}
        >
          <div style={{ height, overflowY: 'auto' }}>
            <IssueList
              data={bpHistory}
              selectedBp={selectedBp}
              onSave={handleIssueSave}
              onIssueSelect={handleIssueSelect}
              onHistoryBpSelected={handleHistoryBpSelect}
              onCollapsed={onCollapsed}
            />
          </div>
        </Tabs.TabPane>
      </Tabs>

      <UploadBlueprint
        targetKey={key}
        initData={selectedBp}
        modalVisible={uploadModalVisible}
        onSave={onUploadPdf}
        onCancel={() => {
          setUploadModalVisible(false);
        }}
      />
    </Spin>
  );
};

export default connect(
  ({
    project,
    loading,
  }: {
    project: StateType;
    loading: {
      effects: { [key: string]: boolean };
      models: { [key: string]: boolean };
    };
  }) => ({
    project,
    loading: loading.models.project,
  }),
)(BlueprintMenu);
